#pragma once

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>



#include "log.hpp"
#include "InetAddr.hpp"
using namespace log_ns;

enum
{
    SOCK_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
};

const static uint16_t gport = 8888;
const static int gsockfd = -1;
const static int gbacklog = 8;

class TcpServer
{
public:
    TcpServer(uint16_t port = gport)
        : _port(port), _listen_sockfd(gsockfd), _is_running(false)
    {
    }

    void init_server()
    {
        // 1.创建套接字
        _listen_sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sockfd < 0)
        {
            LOG(FATAL, "socket error!\n");
            exit(SOCK_ERROR);
        }
        LOG(INFO, "socket create success!\n");

        // 2. bind sockfd 和 sockaddr
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_port);
        addr.sin_addr.s_addr = INADDR_ANY;
        if (::bind(_listen_sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
        {
            LOG(FATAL, "bind error!\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success!\n");

        // 3. 由于tcp是面向连接的，所以需要不断的获取连接
        if (::listen(_listen_sockfd, gbacklog) < 0)
        {
            LOG(FATAL, "listen error!\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen success!\n");
    }

    void loop()
    {
        _is_running = true;
        while (_is_running)
        {
            // 4. 获取新连接
            struct sockaddr_in client_addr;
            socklen_t len = sizeof(client_addr);
            int sockfd = ::accept(_listen_sockfd, (struct sockaddr *)&client_addr, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error!\n");
                continue;
            }
            InetAddr addr(client_addr);
            LOG(INFO, "get a new link, client info %s\n", addr.AddrStr().c_str());

            Service(sockfd, addr);
        }
    }

    void Service(int sockfd, InetAddr addr)
    {
        while (true)
        {
           char inbuffer[1024];
            ssize_t n = ::read(sockfd, inbuffer, sizeof(inbuffer)-1);
            if(n > 0)
            {
                inbuffer[n] = 0;
                std::cout<<"["<<addr.AddrStr()<<"]# "<<inbuffer<<std::endl;
                std::string echo_string = "[server echo]# ";
                echo_string += inbuffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if(n == 0)
            {
                LOG(INFO, "client %s qiut!\n", addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error: %s\n", addr.AddrStr().c_str());
                break;
            }
        }
        ::close(sockfd);
    }

    ~TcpServer() {}

private:
    uint16_t _port;
    int _listen_sockfd;
    bool _is_running;
};